const fs = require('fs');
const path = require('path');

function reslove(fileName) {
  return path.resolve(__dirname, `./${fileName}.json`);
}


function getConfig(fileName) {
  return new Promise((s, f) => {
    fs.readFile(reslove(fileName), function (err, data) {
      if (err) {
        console.warn(`read ${fileName} error`);
        console.log(err);
        return;
      }
      try {
        const config = JSON.parse(data);
        s(config);
      } catch (e) {
        console.warn(`json解析错误`);
        s(null);
      }
    });
  });
}

function updateConfig(options, fileName = 'config') {
  return new Promise((s, f) => {
    const data = JSON.stringify(options);
    console.log('writedata', data);
    fs.writeFile(reslove(fileName), data, 'utf-8', function (err) {
      if (err) {
        console.warn(`write ${fileName} error`);
        console.log(err);
        s(null);
        return;
      }
      s(true);
    });
  });
}

module.exports = {
  getConfig,
  updateConfig
};
